package com.yanqu.road.server.manager.activity.xingyou.inter.grid;

import com.yanqu.road.entity.activity.youxing.CrossXingYouShanShuiTeamActionLogData;
import com.yanqu.road.entity.activity.youxing.CrossXingYouShanShuiTeamMapData;
import com.yanqu.road.entity.activity.youxing.CrossXingYouShanShuiUserData;
import com.yanqu.road.entity.activity.youxing.ShanShuiGridParam;
import com.yanqu.road.entity.activity.youxing.config.XingYouShanShuiEventInfo;
import com.yanqu.road.entity.activity.youxing.config.XingYouShanShuiGridInfo;
import com.yanqu.road.entity.log.cross.xingyou.LogCrossXingYouMove;
import com.yanqu.road.pb.activity.XingYouShanShuiProto;
import com.yanqu.road.server.manager.activity.xingyou.ConfirmHandleResult;
import com.yanqu.road.server.manager.activity.xingyou.CrossXingYouActivity;
import com.yanqu.road.server.manager.activity.xingyou.CrossXingYouShanShuiMgr;
import com.yanqu.road.server.manager.activity.xingyou.DiceHandleResult;
import com.yanqu.road.server.manager.activity.xingyou.enums.eXingYouGridTypes;
import com.yanqu.road.server.manager.activity.xingyou.inter.GridHandleResult;
import com.yanqu.road.server.manager.activity.xingyou.inter.IXingYouGridHandler;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.util.*;

/**
 * 事件格
 */
public class TouchEventHandler implements IXingYouGridHandler {

    @Override
    public void handle(XingYouShanShuiGridInfo gridInfo, int pos, int gridId, int endPos, boolean fly, DiceHandleResult result) {
        //是否停留
        boolean stop = pos == endPos;
        if(!stop){
            return;
        }

        Property fixedReward = result.getActivity().getGridInfoFixedReward(result.getUserData(), gridInfo, true);

        //如果是漂泊模式
        if(result.getUserData().isDrift()){
            //空白格子
            ShanShuiGridParam gridParam = new ShanShuiGridParam(gridId, pos, true, true);
            GridHandleResult gridHandleResult = new GridHandleResult();
            gridHandleResult.setGridParam(gridParam);


            XingYouShanShuiProto.ShanShuiEventInfo.Builder eventBuilder = result.getActivity().getEventInfoBuilder(pos, gridId, fixedReward, true);
            eventBuilder.setFixedReward(PropertyHelper.parsePropertyToString(fixedReward));
            eventBuilder.setAward(PropertyHelper.parsePropertyToString(fixedReward));
            gridHandleResult.setBuilder(eventBuilder);
            result.getGridHandleResultList().add(gridHandleResult);
            return;
        }
        if(fly) {
            //健步如飞，不再触发事件
            ShanShuiGridParam gridParam = new ShanShuiGridParam(gridId, pos, true, false);
            GridHandleResult gridHandleResult = new GridHandleResult();
            gridHandleResult.setGridParam(gridParam);

            XingYouShanShuiProto.ShanShuiEventInfo.Builder eventBuilder = result.getActivity().getEventInfoBuilder(pos, gridId, fixedReward, true);
            eventBuilder.setBaseReward(PropertyHelper.parsePropertyToString(fixedReward));
            result.getActivity().calRewardBuff(result.getUserData(), fixedReward, false, 0);
            eventBuilder.setIsDrift(false);
            eventBuilder.setFixedReward(PropertyHelper.parsePropertyToString(fixedReward));
            eventBuilder.setAward(PropertyHelper.parsePropertyToString(fixedReward));
            gridHandleResult.setBuilder(eventBuilder);

            result.getGridHandleResultList().add(gridHandleResult);
        }else {

            //停留触发事件
            XingYouShanShuiEventInfo eventInfo = result.getConfig().randomXingYouShanShuiEventInfo();
            if(result.getTestEventId() > 0){
                XingYouShanShuiEventInfo info = result.getConfig().getEventInfo(result.getTestEventId());
                if(info != null){
                    eventInfo = info;
                }
            }
            if(result.getUserData().getTestEventId() > 0){
                XingYouShanShuiEventInfo info = result.getConfig().getEventInfo(result.getUserData().getTestEventId());
                if(info != null){
                    eventInfo = info;
                }
                result.getUserData().setTestEventId(0);
            }

            XingYouShanShuiProto.ShanShuiEventInfo.Builder eventBuilder = XingYouShanShuiProto.ShanShuiEventInfo.newBuilder();
            eventBuilder.setPosition(pos);
            eventBuilder.setGridId(gridId);
            eventBuilder.setEventId(eventInfo.getId());
            eventBuilder.setHandle(true);
            eventBuilder.setFixedReward(PropertyHelper.parsePropertyToString(fixedReward));
            //默认只有固定奖励，后面有其他奖励，要合并固定奖励及重新设置
            eventBuilder.setAward(eventBuilder.getFixedReward());

            ShanShuiGridParam gridParam = new ShanShuiGridParam(gridId, pos, true, false);
            if(eventInfo.getId() == 3 || eventInfo.getId() == 2){
                //健步如飞/驿站
                gridParam = new ShanShuiGridParam(gridId, pos, false, false);
                eventBuilder.setHandle(false);
            }
            gridParam.setEventId(eventInfo.getId());

            GridHandleResult gridHandleResult = new GridHandleResult();
            gridHandleResult.setGridParam(gridParam);
            gridHandleResult.setBuilder(eventBuilder);
            result.getGridHandleResultList().add(gridHandleResult);

            //随机传送
            if(eventInfo.getId() == 1){
                List<Integer> shanshuiMap = result.getConfig().getSHANSHUI_MAP();
                if(result.isInMazu()){
                    shanshuiMap = result.getConfig().getSHANSHUI_TOWER_MAP();
                }
                //随机一个非当前的位置
                List<Integer> weightList = new ArrayList<>();
                List<Integer> valueList = new ArrayList<>();
                for (int i = 0; i < shanshuiMap.size(); i++) {
                    if(i == pos){
                        continue;
                    }
                    weightList.add(1);
                    valueList.add(shanshuiMap.get(i));
                }
                int index = RandomHelper.getRandomIndexByWeight(weightList, new Random());
                int position = valueList.get(index);
                int gid = shanshuiMap.get(position);

                CrossXingYouShanShuiTeamActionLogData logData = result.getActivity().createActionLogData(result.getUserData(), XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_EVENT, "",
                        Arrays.asList(String.valueOf(result.getUserData().getRoleId()), String.valueOf(eventInfo.getId()), String.valueOf(gid)));
                result.getActionLogDataList().add(logData);

                XingYouShanShuiGridInfo shuiGridInfo = result.getConfig().getGridInfo(gid);
                result.getActivity().handleGrid(shuiGridInfo, position, gid, position, false, result);

            }else if(eventInfo.getId() == 4 || eventInfo.getId() == 5 || eventInfo.getId() == 15){
                //跳转
                eventBuilder.setEventParam(eventInfo.getParam().get(0));
                List<Integer> shanshuiMap = result.getConfig().getSHANSHUI_MAP();
                int position = eventInfo.getParam().get(0);

                int gid = shanshuiMap.get(position);
                CrossXingYouActivity activity = result.getActivity();

                CrossXingYouShanShuiTeamActionLogData logData = result.getActivity().createActionLogData(result.getUserData(), XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_EVENT, "",
                        Arrays.asList(String.valueOf(result.getUserData().getRoleId()), String.valueOf(eventInfo.getId())));
                result.getActionLogDataList().add(logData);

                if(activity != null) {
                    XingYouShanShuiGridInfo shuiGridInfo = result.getConfig().getGridInfo(gid);
                    activity.handleGrid(shuiGridInfo, position, gid, position, false, result);
                }
            }else if(eventInfo.getId() == 10){
                Property property = new Property();
                property.addProperty(result.getConfig().getSHANSHUI_GOLD_COIN_ID(), eventInfo.getParam().get(0));

                CrossXingYouShanShuiTeamActionLogData logData = result.getActivity().createActionLogData(result.getUserData(), XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_EVENT, PropertyHelper.parsePropertyToString(property),
                        Arrays.asList(String.valueOf(result.getUserData().getRoleId()), String.valueOf(eventInfo.getId())));
                result.getActionLogDataList().add(logData);

                property.addProperty(fixedReward);
                eventBuilder.setAward(PropertyHelper.parsePropertyToString(property));

            }else if(eventInfo.getId() == 11){
                Property property = new Property();
                property.addProperty(result.getConfig().getSHANSHUI_SILVER_COIN_ID(), eventInfo.getParam().get(0));

                eventBuilder.setBaseReward(PropertyHelper.parsePropertyToString(property));
                result.getActivity().calRewardBuff(result.getUserData(), property, false, result.getActivity().getRoleBuffAddition(result.getUserData(), 2));

                CrossXingYouShanShuiTeamActionLogData logData = result.getActivity().createActionLogData(result.getUserData(), XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_EVENT, PropertyHelper.parsePropertyToString(property),
                        Arrays.asList(String.valueOf(result.getUserData().getRoleId()), String.valueOf(eventInfo.getId())));
                result.getActionLogDataList().add(logData);

                property.addProperty(fixedReward);
                eventBuilder.setAward(PropertyHelper.parsePropertyToString(property));

            }else if(eventInfo.getId() == 14){
                Property property = new Property();
                property.addProperty(result.getConfig().getSHANSHUI_EXCLUSIVE_DICE_ID(), eventInfo.getParam().get(0));

                CrossXingYouShanShuiTeamActionLogData logData = result.getActivity().createActionLogData(result.getUserData(), XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_EVENT, PropertyHelper.parsePropertyToString(property),
                        Arrays.asList(String.valueOf(result.getUserData().getRoleId()), String.valueOf(eventInfo.getId())));
                result.getActionLogDataList().add(logData);

                property.addProperty(fixedReward);
                eventBuilder.setAward(PropertyHelper.parsePropertyToString(property));

            }else if(eventInfo.getId() == 8){
                //丰收
                //计算所有建筑的奖励
                CrossXingYouActivity activity = result.getActivity();
                if(activity != null){
                    Property allProperty = new Property();
                    Map<Integer, CrossXingYouShanShuiTeamMapData> dataMap = activity.getCrossXingYouShanShuiTeamMapData(result.getUserData().getTeamId());
                    if(dataMap != null){

                        for (Map.Entry<Integer, CrossXingYouShanShuiTeamMapData> entry : dataMap.entrySet()) {
                            CrossXingYouShanShuiTeamMapData mapData = entry.getValue();
                            XingYouShanShuiGridInfo buildGridInfo = result.getConfig().getGridInfo(mapData.getGridId());
                            if(buildGridInfo.getType() != 2){
                                continue;
                            }
                            if(mapData.getBuildLv() > 0){
                                Property buildingReward = result.getActivity().getBuildingReward(buildGridInfo, result.getConfig(), mapData.getBuildLv(), mapData.getCloseTimes(), false, false);
                                allProperty.addProperty(buildingReward);
                            }
                        }
                        //buf
                        int roleBuf = result.getActivity().getRoleBuffAddition(result.getUserData(), 1);
                        roleBuf += result.getActivity().getRoleBuffAddition(result.getUserData(), 2);

                        eventBuilder.setBaseReward(PropertyHelper.parsePropertyToString(allProperty));
                        result.getActivity().calRewardBuff(result.getUserData(), allProperty, result.isInMazu(), roleBuf, true);

                        if(!allProperty.isNothing()){
                            CrossXingYouShanShuiTeamActionLogData logData = result.getActivity().createActionLogData(result.getUserData(), XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_EVENT,
                                    PropertyHelper.parsePropertyToString(allProperty),
                                    Arrays.asList(String.valueOf(result.getUserData().getRoleId()), String.valueOf(eventInfo.getId())));
                            result.getActionLogDataList().add(logData);
                        }

                        //固定奖励放最后
                        allProperty.addProperty(fixedReward);
                    }
                    eventBuilder.setAward(PropertyHelper.parsePropertyToString(allProperty));
                }
            }else if(eventInfo.getId() == 6){
                int dice = new Random().nextInt(6) + 1;
                Property property = new Property();
                property.addProperty(result.getConfig().getSHANSHUI_SILVER_COIN_ID(), dice * eventInfo.getParam().get(0));

                eventBuilder.setBaseReward(PropertyHelper.parsePropertyToString(property));
                result.getActivity().calRewardBuff(result.getUserData(), property, false, result.getActivity().getRoleBuffAddition(result.getUserData(), 2));
                eventBuilder.setAward(PropertyHelper.parsePropertyToString(property));
                eventBuilder.setEventParam(dice);

                CrossXingYouShanShuiTeamActionLogData logData = result.getActivity().createActionLogData(result.getUserData(), XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_EVENT, eventBuilder.getAward(),
                        Arrays.asList(String.valueOf(result.getUserData().getRoleId()), String.valueOf(eventInfo.getId()), String.valueOf(dice)));
                result.getActionLogDataList().add(logData);

                //固定奖励放最后
                property.addProperty(fixedReward);

            }else if(eventInfo.getId() == 7){
                //扣银票的事件
                int dice = new Random().nextInt(6) + 1;
                eventBuilder.setAward(result.getConfig().getSHANSHUI_SILVER_COIN_ID() + "=-" + dice * eventInfo.getParam().get(0));
                eventBuilder.setEventParam(dice);

                CrossXingYouShanShuiTeamActionLogData logData = result.getActivity().createActionLogData(result.getUserData(), XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_EVENT,
                        "",
                        Arrays.asList(String.valueOf(result.getUserData().getRoleId()), String.valueOf(eventInfo.getId()), String.valueOf(dice), result.getConfig().getSHANSHUI_SILVER_COIN_ID() + "=" + dice * eventInfo.getParam().get(0)));
                result.getActionLogDataList().add(logData);
            }else if(eventInfo.getId() == 9){
                //佛光普照
                result.addWish(eventInfo.getParam().get(0));
            }else if(eventInfo.getId() == 12){
                //buff
                result.addBuff(12, eventInfo.getParam().get(0));

                CrossXingYouShanShuiTeamActionLogData logData = result.getActivity().createActionLogData(result.getUserData(), XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_EVENT, "",
                        Arrays.asList(String.valueOf(result.getUserData().getRoleId()), String.valueOf(eventInfo.getId())));
                result.getActionLogDataList().add(logData);
            }else if(eventInfo.getId() == 13){
                //buff
                result.addBuff(13, eventInfo.getParam().get(0));

                CrossXingYouShanShuiTeamActionLogData logData = result.getActivity().createActionLogData(result.getUserData(), XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_EVENT, "",
                        Arrays.asList(String.valueOf(result.getUserData().getRoleId()), String.valueOf(eventInfo.getId())));
                result.getActionLogDataList().add(logData);
            }else if(eventInfo.getId() == 3){
                //健步如飞日志
//                CrossXingYouShanShuiTeamActionLogData logData = result.getActivity().createActionLogData(result.getUserData(), XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_EVENT, "",
//                        Arrays.asList(String.valueOf(result.getUserData().getRoleId()), String.valueOf(eventInfo.getId()), "?", "?", "?", "?", "?", "?"));
//                logData.setEventId(3);
//                result.getActionLogDataList().add(logData);
            }
        }
    }

    @Override
    public void confirm(XingYouShanShuiGridInfo gridInfo, CrossXingYouShanShuiUserData userData, ConfirmHandleResult handleResult, long select, boolean isDrift) {
        //传送
        CrossXingYouActivity activity = handleResult.getActivity();
        int newPos = (int)select;
        ShanShuiGridParam gridParam = userData.getGridParam();
        if(gridParam.getMapIndex() == newPos){
            handleResult.setRet(GameErrorCode.E_XING_YOU_SHAN_SHUI_NO_NEED_SEND);
            return;
        }
        if(userData.isDrift()){
            return;
        }
        int eventId = gridParam.getEventId();
        if(eventId != 2){
            handleResult.setRet(GameErrorCode.E_XING_YOU_SHAN_SHUI_INFO_OUT_TIME);
            return;
        }
        if(newPos < 0 || newPos > activity.getConfig().getSHANSHUI_MAP().size() - 1){
            handleResult.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
            return;
        }
        int startPos = gridParam.getMapIndex();
        Integer gid = activity.getConfig().getSHANSHUI_MAP().get(newPos);
        if(activity.inMazuTemp(userData)){
            gid = activity.getConfig().getSHANSHUI_TOWER_MAP().get(newPos);
        }
        XingYouShanShuiGridInfo shuiGridInfo = activity.getConfig().getGridInfo(gid);

        LogCrossXingYouMove moveLog = new LogCrossXingYouMove(userData.getUserId(), userData.getActivityId(), userData.getTeamId(), userData.getMapTeamId());
        moveLog.setGroupId(userData.getGroupId());

        //先记录下事件
        CrossXingYouShanShuiTeamActionLogData logData = activity.createActionLogData(userData, XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_EVENT,
                PropertyHelper.parsePropertyToString(handleResult.getReward()),
                Arrays.asList(String.valueOf(userData.getRoleId()), String.valueOf(eventId), String.valueOf(gid)));
        handleResult.getActionLogDataList().add(logData);

        DiceHandleResult result = new DiceHandleResult();
        //标记是事件格跳转；需求去掉了
//        result.setEventGridJump(true);
        result.setActivity(activity);
        result.setConfig(activity.getConfig());
        result.setUserData(userData);
        result.setInMazu(activity.inMazuTemp(userData));
        //内部调用handleGrid，必须都要处理返回的结果，可能有奖励
        activity.handleGrid(shuiGridInfo, newPos, gid, newPos, false, result);

        if(result.getRet() != 0){
            handleResult.setRet(result.getRet());
            return;
        }

        if(gid == eXingYouGridTypes.One.getId()){
            synchronized (result.getActivity().getTeamLocker(userData.getTeamId())){
                userData.setRound(1 + userData.getRound());
            }
        }

        //处理
        //可能是其他格子，会有奖励
        for (GridHandleResult gridHandleResult : result.getGridHandleResultList()) {
            if(gridHandleResult.getGridParam() != null){
                userData.setGridParam(gridHandleResult.getGridParam());
            }
            if(gridHandleResult.getBuilder() != null){
                if(gridHandleResult.getBuilder().hasAward()){
                    handleResult.getReward().addProperty(PropertyHelper.parseStringToProperty(gridHandleResult.getBuilder().getAward()));
                }
                handleResult.getBuilder().addEventInfo(gridHandleResult.getBuilder());
            }
        }

        handleResult.getActionLogDataList().addAll(result.getActionLogDataList());

        moveLog.setRoleId(userData.getRoleId());
        moveLog.setStartPos(startPos);
        moveLog.setEndPos(newPos);
        moveLog.setReward(PropertyHelper.parsePropertyToString(handleResult.getReward()));
        moveLog.setSliverCoin(handleResult.getReward().getCountByGoodsId(result.getConfig().getSHANSHUI_SILVER_COIN_ID()).intValue());
        moveLog.setGoldCoin(handleResult.getReward().getCountByGoodsId(result.getConfig().getSHANSHUI_GOLD_COIN_ID()).intValue());
        moveLog.setBuffInfo(getBuff(gridParam));
        handleResult.getAutoLogList().add(moveLog);

        handleResult.getAutoLogList().addAll(result.getAutoLogList());

        //移动同步
        XingYouShanShuiProto.ShanShuiMoveInfo.Builder moveInfoBuilder = XingYouShanShuiProto.ShanShuiMoveInfo.newBuilder();
        for (GridHandleResult gridHandleResult : result.getGridHandleResultList()) {
            if(gridHandleResult.getBuilder() != null){
                moveInfoBuilder.addEventInfo(gridHandleResult.getBuilder());
            }
            if(gridHandleResult.getGridParam() != null){
                moveInfoBuilder.setEndPosition(gridHandleResult.getGridParam().getMapIndex());
            }
        }
        moveInfoBuilder.setStartPosition(startPos);
        moveInfoBuilder.setPlayerId(userData.getUserId());
        handleResult.setMoveInfoBuilder(moveInfoBuilder);

    }

    private String getBuff(ShanShuiGridParam gridParam) {
        StringBuilder builder = new StringBuilder();
        if(gridParam.getCacheBuf().contains(12)){
            builder.append("12=").append("1").append(",");
        }
        if(gridParam.getCacheBuf().contains(13)){
            builder.append("13=").append("1").append(",");
        }
        return builder.toString();
    }
}
